import {
    createStore,
    applyMiddleware
} from "redux"
import thunk from "redux-thunk"
let initValue = {
    list: window.localStorage.getItem('state') ? JSON.parse(window.localStorage.getItem('state')).list : [],
    allPrice: window.localStorage.getItem('state') ? JSON.parse(window.localStorage.getItem('state')).allPrice : 0,
    allNum: window.localStorage.getItem('state') ? JSON.parse(window.localStorage.getItem('state')).allNum : 0,
    selectNum: 0, //选中的个数
    allChecked: false

}
//计算购物车数据
let calcCart = (list) => {
    let allPrice = 0;
    let allNum = 0;
    let selectNum = 0;
    list.forEach((item) => {
        if (item.num) {
            allNum += item.num
            if (item.checked) {
                allPrice += item.num * item.price;
                selectNum += item.num;
            }
        }
    });

    return {
        allPrice,
        allNum,
        selectNum
    }

}
let reducer = (state = initValue, action) => {


    switch (action.type) {
        case "SET_LIST":
            state.list = action.data;
            state.allPrice = calcCart(state.list).allPrice;
            state.allNum = calcCart(state.list).allNum;
            state.selectNum = calcCart(state.list).selectNum;
            state.allChecked = state.list.filter(item => item.num).every(item => item.checked)
            break;

        case "SELECT_ALL":
            state.allChecked = action.data;
            state.list.forEach(item => item.checked = action.data);

            state.allPrice = calcCart(state.list).allPrice;
            state.allNum = calcCart(state.list).allNum;
            state.selectNum = calcCart(state.list).selectNum;
            break;


        default:




    }
    window.localStorage.setItem('state', JSON.stringify(state));
    return JSON.parse(JSON.stringify(state))
}
export default createStore(reducer, applyMiddleware(thunk))